package com.gome.ocean.service.authority.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.ibatis.session.RowBounds;
import org.elasticsearch.common.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.gome.ocean.dao.authority.FunctionDAO;
import com.gome.ocean.dao.authority.ModuleDAO;
import com.gome.ocean.dao.authority.ProjectDAO;
import com.gome.ocean.dao.datax.DataSourceOAAuthApplyDAO;
import com.gome.ocean.dao.model.authority.Function;
import com.gome.ocean.dao.model.authority.Module;
import com.gome.ocean.dao.model.authority.ProjectBO;
import com.gome.ocean.dao.model.authority.ReplaceFun;
import com.gome.ocean.dao.model.datasource.DataSourceAuthorityOAApplyBean;
import com.gome.ocean.dao.model.datasource.LabelBean;
import com.gome.ocean.service.authority.FunctionService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * Created by liuqingxia on 2016/6/1.
 */
@Service
public class FunctionServiceImpl implements FunctionService {

    @Resource(name = "functionDAO")
    private FunctionDAO              functionDAO;
    @Autowired
    private ModuleDAO                moduleDAO;
    @Autowired
    private ProjectDAO               projectDao;
    @Autowired
    private DataSourceOAAuthApplyDAO dataSourceAuthDao;

    @Override
    public boolean insertFunction(Function function) {
        return functionDAO.insertFunction(function) == 1;
    }

    @Override
    public boolean removeFunction(Long id) {
        return functionDAO.removeFunctionById(id) == 1;
    }

    @Override
    public boolean updateFunction(Function function) {
        return functionDAO.updateFunction(function) == 1;
    }

    @Override
    public Function findFunctionById(Long id) {
        return functionDAO.findFunctionById(id);
    }

    @Override
    public List<Function> findFunctionByUrl(String url) {
        List<Function> list = functionDAO.findFunctionByUrl(url);
        this.addParams(list);
        return list;
    }

    @Override
    public Page<Function> findAllFunctions(int pageNum, int pageSize) {
        List<Function> list = functionDAO.findAllFunctions(new RowBounds(pageNum, pageSize));
        this.addParams(list);
        return (Page<Function>) list;
    }

    @Override
    public List<Function> findFunctionsByIds(List<Long> ids) {
        return functionDAO.findFunctionsByIds(ids);
    }

    @Override
    public Map<String, List<Function>> findFunctionGroupByModule() {
        Map<String, List<Function>> functionGroupByModule = Maps.newHashMap();
        List<Module> modules = moduleDAO.findAllModule();
        for (Module module : modules) {
            List<Function> functions = functionDAO.findFunctionByModuleId(module.getId());
            functionGroupByModule.put(module.getName(), functions);
        }
        return functionGroupByModule;
    }

    private List<Function> addParams(List<Function> list) {
        if (list != null && list.size() > 0) {
            for (Function func : list) {
                Module module = moduleDAO.findModuleById(Long.parseLong(func.getModule().toString()));
                func.setModuleName(module.getName());
            }
            return list;
        }
        return null;
    }

    @Override
    public List<Function> findFuncByUrlAndType(String url, Integer methodType) {
        try {
            List<Function> list = functionDAO.findFunctionByUrlAndType(url, methodType);
            if (list != null && list.size() > 0) {
                return list;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean batchUpdateSqlValue(Map<String, Object> map) {
        boolean flag = false;
        try {
            if (map != null && map.size() > 0) {
                String tableName = map.get("tableName").toString();
                String fieldName = map.get("fieldName").toString();
                List<ReplaceFun> idLists = functionDAO.getAllIdByTableName(tableName);
                if (idLists != null && idLists.size() > 0) {
                    if (tableName.equals("t_project") && fieldName.equals("project_user")) {
                        for (ReplaceFun idList : idLists) {
                            ProjectBO project = projectDao.findProjectById(idList.getId());
                            if (project != null) {
                                Map<String, Object> proMap = Maps.newHashMap();
                                StringBuilder sb = new StringBuilder();
                                proMap.put("id", idList.getId());
                                proMap.put("tableName", tableName);
                                proMap.put("fieldName", fieldName);
                                if (StringUtils.isNotBlank(project.getProjectUser())) {
                                    String[] valueStr = project.getProjectUser().split(",");
                                    for (String str : valueStr) {
                                        String[] subEmailArray = str.split("@");
                                        if (str.contains("gomeplus")) {
                                            sb.append(str).append(",");
                                        } else {
                                            sb.append(subEmailArray[0]).append("@gomeplus.com").append(",");
                                        }
                                    }
                                    String replaceStr = sb.deleteCharAt(sb.length() - 1).toString();
                                    proMap.put("replaceValue", "'" + replaceStr + "'");
                                    functionDAO.updateFieldEmailByTableAndId(proMap);

                                }
                            }
                        }
                        flag = true;
                    } else if (tableName.equals("tb_oa_datasource") && fieldName.equals("member")) {
                        for (ReplaceFun idList : idLists) {
                            Map<String, Object> dataAuthMap = Maps.newHashMap();
                            dataAuthMap.put("id", idList.getId());
                            DataSourceAuthorityOAApplyBean dataAuth = dataSourceAuthDao.getBeanByMap(dataAuthMap);
                            if (dataAuth != null) {
                                String member = dataAuth.getMember();
                                if (StringUtils.isNotBlank(member)) {
                                    List<LabelBean> labelLists = JSONArray.parseArray(member, LabelBean.class);
                                    List<LabelBean> beanLists = Lists.newArrayList();
                                    if (labelLists != null && labelLists.size() > 0) {
                                        for (LabelBean label : labelLists) {
                                            LabelBean lb = new LabelBean();
                                            lb.setEdept(label.getEdept());
                                            if (label.getEmail().contains("gomeplus")) {
                                                lb.setEmail(label.getEmail());
                                            } else {
                                                lb.setEmail(label.getEmail().replaceAll("yolo24", "gomeplus"));
                                            }
                                            beanLists.add(lb);
                                        }
                                        Map<String, Object> upParam = Maps.newHashMap();
                                        upParam.put("id", idList.getId());
                                        upParam.put("tableName", tableName);
                                        upParam.put("fieldName", fieldName);
                                        upParam.put("replaceValue", "'" + JSON.toJSONString(beanLists) + "'");
                                        functionDAO.updateFieldEmailByTableAndId(upParam);
                                    }
                                }
                            }
                        }
                        flag = true;
                    } else {
                        for (ReplaceFun idList : idLists) {
                            Map<String, Object> paramMap = Maps.newHashMap();
                            paramMap.put("id", idList.getId());
                            paramMap.put("tableName", tableName);
                            paramMap.put("fieldName", fieldName);
                            ReplaceFun replaceFun = functionDAO.getReplaceStrByTableNameAndId(paramMap);
                            if (replaceFun != null) {
                                Map<String, Object> updateMap = Maps.newHashMap();
                                if (StringUtils.isNotBlank(replaceFun.getReplaceStr())) {
                                    if (!replaceFun.getReplaceStr().contains("@g")) {
                                        updateMap.put("id", idList.getId());
                                        updateMap.put("replaceValue",
                                            "'" + replaceFun.getReplaceStr().concat("@gomeplus.com") + "'");
                                        updateMap.put("fieldName", fieldName);
                                        updateMap.put("tableName", tableName);
                                        functionDAO.updateFieldEmailByTableAndId(updateMap);
                                    }
                                }
                            }
                        }
                        flag = true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }
}
